// Copyright (c) 1996-2002 John Lyon-Smith. All rights reserved.

#pragma once

#include <wxtl\Base.h>
#include <wxtl\StringUtil.h>
#include <wxtl\TextFile.h>

// TODO: This class doesn't yet support the Windows [section] format, and is currently read-only.

namespace wxtl
{
	class IniFile
	{
	private:
		typedef hash_map<tstring, tstring> Vars;
		
		
		Vars m_vars;

	public:
		typedef Vars::const_iterator VarsConstIterator;
		typedef Vars::iterator VarsIterator;
		void load(const TCHAR* file) throw(...)
		{
			TextFile textFile;

			textFile.open(file);

			char buffer[512];
			DWORD dwActual;
			
			while (textFile.readLine(buffer, ARRAYSIZE(buffer), dwActual) && 
				buffer[dwActual] == 0)
			{
				char* p = buffer;

				while (*p && isspace(*p))
					p++;

				if (*p == 0) // Empty line
					continue;
				else if (*p == ';' || *p == '#') // Comment
					continue;
				
				#ifdef _UNICODE
				tstring line(asciiToUnicode(buffer));
				#else
				tstring line(buffer);
				#endif
				size_t index = line.find('=');

				if (index != string::npos)
				{
					tstring var(line, 0, index);
					tstring val(line, index+1);
			
					if (var.size() == 0 || val.size() == 0)
						continue;

					m_vars.insert(Vars::value_type(trim(var), trim(val)));
				}
			}
		}

		bool get(const TCHAR* pszName, tstring& strValue) const
		{ 
			VarsConstIterator i = find(tstring(pszName));
			
			if (i == end())
			{
				strValue.clear();
				return false;
			}
			else
			{
				strValue = i->second;
				return true;
			}
		}

		size_t size()
		{
			return m_vars.size();
		}

		VarsConstIterator begin() const
		{
			return m_vars.begin();
		}
		
		VarsConstIterator end() const
		{
			return m_vars.end();
		}

		void erase(VarsIterator i)
		{
			m_vars.erase(i);
		}
		
		VarsConstIterator find(const tstring& s) const
		{
			return m_vars.find(s);
		} 
	};
}

